package webserv

import (
	"cm2"
	"cm2/service"
	"cm2/service/irisweb"
	"cm2/service/log"
	"cm2/util"
	"fmt"

	"github.com/go-xorm/xorm"

	"cm2/terminal/console/win/global"
	taskArea "cm2/terminal/console/win/webserv/area/task"
	workerArea "cm2/terminal/console/win/webserv/area/worker"
)

// RunConsoleWebService 启动控制台 web service
func RunConsoleWebService(db *xorm.Engine) {
	log.DefaultLogger().Info("launching console web service")
	global.WebServShutdown = make(chan bool, 1)

	cwConfig := service.DefaultConfig["consoleWebServer"].(map[string]interface{})
	cwAddr := cwConfig["addr"].(string)
	cwPort := int(cwConfig["port"].(float64))
	cwAddress := fmt.Sprintf("%s:%d", cwAddr, cwPort)

	cws := irisweb.New(fmt.Sprintf("console web service (%s @ %s)", service.SName, service.SId))
	// 设置监听地址
	cws.SetAddr(cwAddress)
	// 设置数据库
	cws.SetDBProvider(db)
	// 设置日志
	cwLoggerConf := cwConfig["log"].(map[string]interface{})
	cws.Logger(
		cwLoggerConf["name"].(string),
		cwLoggerConf["level"].(string),
		cwLoggerConf["path"].(string),
	)
	// 注册默认的异常恢复处理
	cws.RegisterDefaultRecoverHandler()
	// 注册默认的错误处理
	cws.RegisterDefaultErrorHandler()

	// 放置区域
	var areaPath string
	var handlers []irisweb.HandlerOption
	// areaPath, handlers = demoArea.DemoArea()
	if util.GetGOENV() == cm2.DEV {
		cors := irisweb.CorsOption{AllowedOrigins: []string{"*"}}
		areaPath, handlers = taskArea.Area()
		cws.RegisterAreaWithCors(areaPath, handlers, cors)

		areaPath, handlers = workerArea.Area()
		cws.RegisterAreaWithCors(areaPath, handlers, cors)

	} else {
		areaPath, handlers = taskArea.Area()
		cws.RegisterArea(areaPath, handlers)

		areaPath, handlers = workerArea.Area()
		cws.RegisterArea(areaPath, handlers)
	}

	// 注册为默认的webapp
	service.RegisterWebapp("default", cws)

	// 以 routine 开启 web service
	go func() {
		cws.Start()
		global.WebServShutdown <- true
	}()
}
